package com.intellif.dbutils;


import com.intellif.vo.DBTypeEnum;

/**
 * @author by mozping
 * @Classname DBContextHolder
 * @Description 持有数据源的线程选择数据源，通过ThreadLocal实现线程安全，
 * 通过set选择的key来实现数据源的切换
 * @Date 2019/11/12 11:14
 */
public class DBContextHolder {
    /**
     * 保存切换数据源的key
     */
    private static final ThreadLocal<DBTypeEnum> contextHolder
            = new ThreadLocal<DBTypeEnum>();

    public static void set(DBTypeEnum dbTypeEnum) {
        contextHolder.set(dbTypeEnum);
    }

    public static DBTypeEnum get() {
        return contextHolder.get();
    }

    public static void master() {
        set(DBTypeEnum.MASTER);
        System.out.println("切换到 MASTER ... ");
    }

    public static void slave() {
        //此处如果有多个Slave，可以自定义set选择的规则
        set(DBTypeEnum.SLAVE);
        System.out.println("切换到 SLAVE ... ");
    }

}
